package com.yksj.healthtalk.ui.setting;

import org.universalimageloader.core.ImageLoader;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.open.share.ContextMgr;
import com.open.share.OpenManager;
import com.open.share.interfaces.IOpenResponse;
import com.open.share.net.AbstractRunnable;
import com.open.share.net.NetPool;
import com.open.share.sina.SinaShareImpl;
import com.open.share.sina.SinaTokenBean;
import com.open.share.sina.SinaUserInfo;
import com.open.share.utils.SharedPreferenceUtil;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog.OnDilaogClickListener;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.comm.RootFragment;
import com.yksj.healthtalk.db.ChatUserHelper;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.CoreService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.RingPlayer;
import com.yksj.healthtalk.ui.app.AppManager;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.app.SettingManager;
import com.yksj.healthtalk.ui.login.UserLoginUI;
import com.yksj.healthtalk.utils.HStringUtil;
import com.yksj.healthtalk.utils.PopWindowUtil;
import com.yksj.healthtalk.utils.SharePreUtils;
import com.yksj.healthtalk.utils.SystemUtils;
import com.yksj.healthtalk.utils.ToastUtil;
import com.yksj.healthtalk.utils.ViewFinder;
import com.yksj.healthtalk.utils.ViewUtils;

public class SettingMainUI extends RootFragment implements OnClickListener,
		OnCheckedChangeListener {

	private ToggleButton publicCheckBox;// 公开位置
	private ToggleButton soundIsOpenTog;// 开启按键音效
	private ToggleButton shackIsOpenTog;// 开启震动提示
	private ToggleButton pushIsOpenTog;// 开启推送健康贴士
	private PopupWindow pop;
	private TextView weibo_text;// 微博
	private ChatUserHelper mDictionaryHelper;
	public long CLICKWHICH = 0;
	private CustomerInfoEntity mEntity;

	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
		public void onReceive(android.content.Context context,
				android.content.Intent intent) {
			String action = intent.getAction();
			if (CoreService.ACTION_EXIT.equalsIgnoreCase(action)) {
				int result = intent.getIntExtra(SmartFoxClient.KEY_PARAME, -1);
				LodingFragmentDialog.dismiss(getFragmentManager());
				if (result == 1) {

				} else {
					ToastUtil.showShort(context, R.string.groupNewFail);
				}
			} else if (OpenManager.AUTH_RESULT_ACTION
					.equals(intent.getAction())) {
				onReqUserInfo();
			}
		}

	};
	private View v;

	/**
	 * 退出
	 */
	private void logout() {
		CoreService.actionLogout(HTalkApplication.getApplication());
		Intent intent = new Intent();
		intent.setClass(getActivity(),UserLoginUI.class);
		startActivity(intent);
	}

	private void onReqUserInfo() {
		SinaShareImpl shareImpl = new SinaShareImpl();
		AbstractRunnable runnable = shareImpl.getUserInfo(new Bundle(),
				new IOpenResponse() {
					@Override
					public boolean response(int arg0, Object arg1) {
						SinaUserInfo userInfo = (SinaUserInfo) arg1;
						if (arg1 != null) {
							sendBindUserInfo(userInfo.name);
						}
						return false;
					}
				});
		NetPool.getInstance().push(runnable);
	}

	private void sendBindUserInfo(final String name) {
		final SinaTokenBean out = new SinaTokenBean();
		SharedPreferenceUtil.Fetch(ContextMgr.getContext(), OpenManager
				.getInstatnce().getSpName(OpenManager.SINA_WEIBO), out);
		getActivity().runOnUiThread(new Runnable() {
			@Override
			public void run() {
				HttpRestClient.doHttpBundSina(name, out.access_token, out.uid,
						mEntity.getId(),out.expires_in, new AsyncHttpResponseHandler() {
							public void onSuccess(String content) {
								if (!isDetached()) {
									LodingFragmentDialog.dismiss(getFragmentManager());
									if ("Y".equalsIgnoreCase(content)) {
										ToastUtil.showBasicShortToast(getActivity(), "已绑定成功");
										weibo_text.setText(name);
										mEntity.setMicroBlogCode(name);
										mEntity.setSetBindSinaState("1");
										if (CLICKWHICH == R.id.invite_sina_friends) {
											Intent intent = new Intent(getActivity(),SettingShareActivity.class);
											startActivity(intent);
											CLICKWHICH = 0;
										}
									} else {
										SharedPreferenceUtil.clear(ContextMgr.getContext(),
												OpenManager.getInstatnce().getSpName(OpenManager.SINA_WEIBO));
									}
								}
							};

							public void onFailure(Throwable error) {
								LodingFragmentDialog.dismiss(getFragmentManager());
								SharedPreferenceUtil.clear(ContextMgr.getContext(),OpenManager.getInstatnce().getSpName(OpenManager.SINA_WEIBO));
								ToastUtil.showBasicErrorShortToast(getActivity());
							}
						});
			}
		});
	}

	@Override
	public void onStart() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(OpenManager.AUTH_RESULT_ACTION);
		filter.addAction(CoreService.ACTION_EXIT);
		getActivity().registerReceiver(mBroadcastReceiver, filter);
		super.onStart();
	}

	
	@Override
	public void onStop() {
		super.onStop();
		setSharedPreferences();
	}
	@Override
	public void onDestroy() {
		super.onDestroy();
		getActivity().unregisterReceiver(mBroadcastReceiver);
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.setting_layout_main, null);
		v = view;
		initUI();
		return view;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initData();
	}
	
	private void initUI() {
		initTitleView(v);
		titleLeftBtn.setOnClickListener(this);
		titleTextV.setText(getString(R.string.setting));
		
		ViewFinder finder=new ViewFinder(v);
		int[] ids=new int[]{R.id.setting_my_bindingweibo,R.id.phone_safe,R.id.email_safe,R.id.setting_password,R.id.public_place
		,R.id.invite_sina_friends,R.id.invite_sms_friends,R.id.setting_update,R.id.setting_feedback,R.id.setting_clear_cache,	
		R.id.setting_my_code,R.id.logout_btn};
		
		finder.onClick(this, ids);
		weibo_text = (TextView) v.findViewById(R.id.weibo_text);

		pushIsOpenTog = (ToggleButton) v.findViewById(R.id.setting_pullAttention);
		publicCheckBox = (ToggleButton) v.findViewById(R.id.public_place);
		soundIsOpenTog = (ToggleButton) v.findViewById(R.id.sound_open);
		shackIsOpenTog = (ToggleButton) v.findViewById(R.id.shack_on_off);

		v.findViewById(R.id.setting_clear_cache).setOnClickListener(this);
		
		SettingManager manager = SettingManager.getInstance();
		publicCheckBox.setChecked(manager.isLocationShare());
		soundIsOpenTog.setChecked(manager.isSoundOpen());
		shackIsOpenTog.setChecked(manager.isVibrateOpen());
		pushIsOpenTog.setChecked(manager.isSendIos());
/*		publicCheckBox.setOnCheckedChangeListener(this);
		soundIsOpenTog.setOnCheckedChangeListener(this);
		shackIsOpenTog.setOnCheckedChangeListener(this);
		pushIsOpenTog.setOnCheckedChangeListener(this);*/
		soundIsOpenTog.setOnCheckedChangeListener(this);
		shackIsOpenTog.setOnCheckedChangeListener(this);
		View mClearCacheV = getActivity().getLayoutInflater().inflate(R.layout.setting_leave, null);
		mClearCacheV.findViewById(R.id.setting_leave_qingchuhuancun).setOnClickListener(this);
		mClearCacheV.findViewById(R.id.setting_leave_quxiao).setOnClickListener(this);

	}

	/**
	 * 保存开关状态
	 */
	public void setSharedPreferences() {
		SettingManager manager = SettingManager.getInstance();
		manager.setLocationShare(publicCheckBox.isChecked());
		manager.setSoundOpen(soundIsOpenTog.isChecked());
//		manager.setSendIos(shackIsOpenTog.isChecked());
		manager.setVibrateOpen(shackIsOpenTog.isChecked());
		/*manager.set
		manager.setLocationShare(publicCheckBox.isChecked());
		manager.setLocationShare(publicCheckBox.isChecked());
		SettingUtil.saveSettingLocation(getActivity(),);
		SettingUtil.saveSettingSound(getActivity(), );
		SettingUtil.saveSettingShack(getActivity(), );
		SettingUtil.saveSettingPush(getActivity(), pushIsOpenTog.isChecked());*/
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.setting_my_code:
			intent = new Intent(getActivity(),SettingQrCodeActivity.class);
			intent.putExtra("id", SmartFoxClient.getLoginUserId());
			intent.putExtra("type", 0);
			startActivity(intent);
			break;
		case R.id.title_back:
			onBackPressed(v);
			break;
		case R.id.setting_my_bindingweibo:// 绑定微博
			CLICKWHICH=0;
			if (!"1".equals(mEntity.getSetBindSinaState())) {
				OpenManager.getInstatnce().authorize(OpenManager.SINA_WEIBO,getActivity());
			} else {
				intent = new Intent(getActivity(), SettingSinaWeiBoBound.class);
				startActivityForResult(intent, 4);
			}
			break;

		case R.id.phone_safe:// 账号安全(绑定手机)
			intent = new Intent(getActivity(), SettingPhoneBound.class);
			startActivityForResult(intent, 2);
			break;
		case R.id.email_safe:// 账号安全(邮箱)
			intent = new Intent(getActivity(), SettingEmailBound.class);
			startActivityForResult(intent, 2);
			break;
		case R.id.setting_password:// 设定密码
			intent = new Intent(getActivity(), SettingPassWordUI.class);
			startActivity(intent);
			break;
		case R.id.invite_sina_friends:// 邀请新浪微博好友
			CLICKWHICH = R.id.invite_sina_friends;
			if (!"1".equals(mEntity.getSetBindSinaState())) {
				OpenManager.getInstatnce().authorize(OpenManager.SINA_WEIBO,getActivity());
			} else {
				intent = new Intent(getActivity(), SettingShareActivity.class);
				startActivity(intent);
			}
			break;
		case R.id.setting_update:// 关于壹健康
			intent = new Intent(getActivity(), SettingAboutHealthActivity.class);
			startActivity(intent);
			break;
		case R.id.setting_feedback:// 意见反馈
			intent = new Intent(getActivity(), SettingFeedbackUI.class);
			startActivity(intent);
			break;
		case R.id.setting_clear_cache:// 清理缓存
			DoubleBtnFragmentDialog.showDefault(getFragmentManager(), "            是否清理缓存", "取消", "确定", new OnDilaogClickListener() {
				
				@Override
				public void onDismiss(DialogFragment fragment) {
					fragment.dismiss();
				}
				@Override
				public void onClick(DialogFragment fragment, View v) {
					clearAllCache();
				}
			});
			
			break;
		case R.id.logout_btn://退出
			PopWindowUtil.showWindow(v, getActivity(),getActivity().getLayoutInflater(),R.layout.window_logout_layout,this);
			break;
		case R.id.exit://退出
			CoreService.actionLogout(getActivity());
			AppManager.getInstance().finishAllActivity();
			intent = new Intent(getActivity(),UserLoginUI.class);
			startActivity(intent);
			break;
		case R.id.setting_leave_qingchuhuancun:// 清除缓存的pop
			clearAllCache();
			pop.dismiss();
			break;
		case R.id.setting_leave_quxiao:
			if (pop != null && pop.isShowing())
				pop.dismiss();
			break;
		case R.id.invite_sms_friends:// 短信
			sendSMS();
			break;

		}

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 4:
			mEntity = SmartFoxClient.getSmartFoxClient().getCustomerInfoEntity();
			if (!mEntity.getSetBindSinaState().equals("1")) {
				mEntity.setMicroBlogCode("");
				weibo_text.setText("");
			}
			if("1".equals(mEntity.getSetBindSinaState()))
			weibo_text.setText(mEntity.getMicroBlogCode() + "");
			break;
		case 3:
			initData();
			break;

		}
	}

	@Override
	public void onResume() {
		super.onResume();
		mEntity = SmartFoxClient.getSmartFoxClient().getCustomerInfoEntity();
		mDictionaryHelper = ChatUserHelper.getInstance();
		ImageView mPhoneIcon = (ImageView) v.findViewById(R.id.phone_icon);
		ImageView mEmailIcon = (ImageView) v.findViewById(R.id.email_icon);
		if (mEntity != null) {
			if (mEntity.getPoneNumber() != null&& !mEntity.getPoneNumber().trim().equals("")) {
				mPhoneIcon.setVisibility(View.VISIBLE);
			} else {
				mPhoneIcon.setVisibility(View.GONE);
			}
			
			if (mEntity.getEmail() != null&& !mEntity.getEmail().trim().equals("")) {
				mEmailIcon.setVisibility(View.VISIBLE);
			} else {
				mEmailIcon.setVisibility(View.GONE);
			}
			
				if("1".equals(mEntity.getSetBindSinaState())) {
				weibo_text.setText(mEntity.getMicroBlogCode() + "");
				}
			}
	}
	/**
	 * 清理缓存
	 */
	private void clearAllCache() {
		new AsyncTask<Void, Void, Void>() {
			private LodingFragmentDialog showLodingDialog;
			@Override
			protected void onPreExecute() {
				showLodingDialog = LodingFragmentDialog.showLodingDialog(getFragmentManager(),getResources());
			}
			@Override
			protected Void doInBackground(Void... params) {
				ImageLoader.getInstance().clearDiscCache();
				return null;
			}
			@Override
			protected void onPostExecute(Void result) {
				showLodingDialog.dismissAllowingStateLoss();
				ToastUtil.showToastPanl( "清理完毕");
			}
		}.execute();
	}

	/**
	 * 显示退出登录对话框
	 */
	public void showLogoutDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setCancelable(false);
		builder.setIcon(android.R.drawable.ic_dialog_info);
		builder.setTitle(R.string.jiankangliao);
		builder.setMessage(R.string.outremind);
		builder.setPositiveButton(R.string.outLogin,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						LodingFragmentDialog.showLodingDialog(getFragmentManager(), getResources());
						SharePreUtils.setCancel(getActivity(), true);
						logout();
						ifServerParame();// 注销登录
					}
				});
		builder.setNegativeButton(R.string.cancel, null);
		builder.show();
	}

	/**
	 * 是否注销登录
	 */
	public void ifServerParame() {
		SmartFoxClient.ifServerParame(SystemUtils.getImeiId());
	}

	/**
	 * 显示更改密码对话框
	 */
	public void showSettingPrivacyDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setCancelable(false);
		builder.setIcon(android.R.drawable.ic_dialog_info);
		builder.setTitle(R.string.jiankangliao);
		builder.setMessage(R.string.privacyremind);
		builder.setPositiveButton(R.string.setPrivacy,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						/**
						 * 设置密码
						 */
						Intent intent = new Intent(getActivity(),
								SettingPassWordUI.class);
						startActivity(intent);
					}
				});
		builder.setNegativeButton(R.string.cancel, null);
		builder.show();
	}


	/**
	 * 发送是否公开位置信息
	 */
	public void ifPublicPlace() {
		if (publicCheckBox.isChecked()) {
			SmartFoxClient.ifPublicLocation("1");
		} else {
			SmartFoxClient.ifPublicLocation("0");
		}
	}

	/**
	 * 发送是否推送健康贴士
	 */
	public void ifPushAttention() {
		if (pushIsOpenTog.isChecked()) {
			SmartFoxClient.ifPushAttention("1");
		} else {
			SmartFoxClient.ifPushAttention("0");
		}
	}


	/**
	 * 初始化数据
	 */
	private void initData() {
		mEntity = SmartFoxClient.getSmartFoxClient().getCustomerInfoEntity();
		mDictionaryHelper = ChatUserHelper.getInstance();
		ImageView mPhoneIcon = (ImageView) v.findViewById(R.id.phone_icon);
		ImageView mEmailIcon = (ImageView) v.findViewById(R.id.email_icon);
		if (mEntity != null) {
			ViewUtils.setGone(mPhoneIcon, HStringUtil.isEmpty(mEntity.getPoneNumber()));
			ViewUtils.setGone(mEmailIcon, HStringUtil.isEmpty(mEntity.getEmail()));
			if("1".equals(mEntity.getSetBindSinaState()))
			weibo_text.setText(mEntity.getMicroBlogCode() + "");
		}
	}

	/**
	 * 短信邀请好友
	 */
	public void sendSMS() {
		Uri smsToUri = Uri.parse("smsto:");
		Intent mIntent = new Intent(android.content.Intent.ACTION_SENDTO,
				smsToUri);
		String DOWNLOAD_URL = "http://yijiankangv.mobi/SJ/download.html";
		mIntent.putExtra("sms_body",getResources().getString(R.string.sms_content) + DOWNLOAD_URL);
		startActivity(mIntent);
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		switch (buttonView.getId()) {
		case R.id.sound_open:
			if (isChecked) {
				RingPlayer.playPressSound(getActivity());
			}
			break;
		case R.id.shack_on_off:
			if (isChecked) {
				SystemUtils.startVibrator(getActivity());
			}
			break;
		}
		
	}
}
